<?php


namespace app\strategy\pay;


use app\common\OrderStatus;
use app\models\order\OrderDetailModel;
use app\models\order\OrderModel;
use app\models\user\TechnicianModel;
use app\models\user\UserModel;
use app\services\order\OrderService;
use app\services\user\DetailMoneyService;
use think\facade\Db;

class BalancePay implements PayInterface
{

    function pay($userId, $orderSn, $amount, $subject, $notifyUrl)
    {
        Db::startTrans();
        try {

            // 扣除用户余额
            $userInfo = UserModel::find($userId);
            if (!$userInfo) {
                throw new \Exception('用户不存在');
            }
            if ($userInfo['money'] < $amount) {
                throw new \Exception('余额不足');
            }
            // 余额变更记录
            $type = DetailMoneyService::ORDER_PAY;


            DetailMoneyService::create($userId, $type, $amount, 0, $orderSn, DetailMoneyService::getTypeText($type));

            OrderService::orderPay($orderSn, '');
            Db::commit();
        } catch (\Exception $exception) {
            Db::rollback();
            throw new \Exception($exception->getMessage());
        }
    }

    function refund($orderId, $cancelType)
    {
        try {

            $order = OrderModel::find($orderId);
            //计算退款金额
            $amount = OrderService::getOrderRefundAmount($order);
            // 退给客户的金额
            $refundAmount = $amount['return_money'];
            // 技师获得金额
            $techGetAmount = $amount['tech_get_money'];

            // 更新订单信息
            $order->order_status = 0;
            $order->refund_price = $refundAmount;
            $order->order_status = OrderStatus::ORDER_CANCEL;
            $order->cancel_time = time();
            $order->cancel_type = $cancelType;
            $order->save();

            //记录余额变更记录
            $type = DetailMoneyService::RETURN;
            DetailMoneyService::create($order['user_id'], $type, $refundAmount, 0, $order['order_sn'], DetailMoneyService::getTypeText($type));

            // 技师余额变更记录
            if ($techGetAmount > 0) {
                $type = DetailMoneyService::REFUND_GET_FEE;
                DetailMoneyService::techCreate($order['tec_id'], $type, $techGetAmount, 0, $order['order_sn'], DetailMoneyService::getTypeText($type));
            }
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }
    }
}